package com.sc.vessel.info.editor;

import java.util.Iterator;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.emf.cdo.util.CommitException;
import org.eclipse.emf.common.util.EList;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.EditorPart;

import com.cs.vessel.breakdown.Activator;
import com.cs.vessel.breakdown.CDOHibernateUtil;
import com.cs.vessel.breakdown.view.providers.AccidentViewContentProvider;
import com.cs.vessel.breakdown.view.providers.AccidentViewLabelProvider;
import com.sc.vessel.info.model.breakdown.Accident;
import com.sc.vessel.info.model.breakdown.ConfigElement;
import com.sc.vessel.info.model.breakdown.Configuration;

public class AccidentEditor extends EditorPart {

    public static final String ID = "com.sc.vessel.info.editor.AccidentEditor"; //$NON-NLS-1$

    private TableViewer viewer;

    private AccidentInput accidentInput;

    private Action editAccidentAction;

    private Action refreshAction;

    private Action deleteActoin;

    public AccidentEditor() {
        // TODO Auto-generated constructor stub
    }

    @Override
    public void doSave(IProgressMonitor monitor) {
        // TODO Auto-generated method stub

    }

    @Override
    public void doSaveAs() {
        // TODO Auto-generated method stub

    }

    @Override
    public void init(IEditorSite site, IEditorInput input) throws PartInitException {
        setSite(site);
        setInput(input);
        accidentInput = (AccidentInput) input;
        setPartName(accidentInput.getComponent().getName() + ": " + Messages.AccidentEditor_2); //$NON-NLS-1$
    }

    @Override
    public boolean isDirty() {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public boolean isSaveAsAllowed() {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public void createPartControl(Composite parent) {
        // this viewer could be change to be a TableTreeViewer
        parent.setLayout(new GridLayout());
        // parent.setBackground(parent.getDisplay().getSystemColor(SWT.COLOR_BLUE));
        GridData gridData = new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL
                | GridData.GRAB_VERTICAL);
        viewer = new TableViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
        viewer.getTable().setHeaderVisible(true);
        viewer.getTable().setLinesVisible(true);
        addColumns(viewer.getTable());
        viewer.setContentProvider(new AccidentViewContentProvider());
        viewer.setLabelProvider(new AccidentViewLabelProvider());
        viewer.setInput(accidentInput);

        viewer.getTable().setLayoutData(gridData);
        // viewer.getTable().setBackground(parent.getDisplay().getSystemColor(SWT.COLOR_RED));

        makeActions();
        hookContextMenu();
        hookDoubleClickAction();
    }

    /**
     * DOC liaoqc Comment method "hookDoubleClickAction".
     */
    private void hookDoubleClickAction() {
        viewer.addDoubleClickListener(new IDoubleClickListener() {

            public void doubleClick(DoubleClickEvent event) {
                editAccidentAction.run();
            }
        });
    }

    /**
     * DOC liaoqc Comment method "hookContextMenu".
     */
    private void hookContextMenu() {
        MenuManager mgr = new MenuManager();
        mgr.setRemoveAllWhenShown(true);
        mgr.addMenuListener(new IMenuListener() {

            public void menuAboutToShow(IMenuManager manager) {
                fillContextMenu(manager);
            }
        });
        Menu menu = mgr.createContextMenu(viewer.getControl());
        viewer.getControl().setMenu(menu);
        getSite().registerContextMenu(mgr, viewer);
    }

    /**
     * DOC liaoqc Comment method "fillContextMenu".
     * 
     * @param manager
     */
    protected void fillContextMenu(IMenuManager manager) {
        manager.add(editAccidentAction);
        manager.add(refreshAction);
        manager.add(new Separator());
        manager.add(deleteActoin);
    }

    /**
     * DOC liaoqc Comment method "makeActions".
     */
    private void makeActions() {
        editAccidentAction = new Action() {

            /*
             * (non-Javadoc)
             * 
             * @see org.eclipse.jface.action.Action#run()
             */
            @Override
            public void run() {
                ISelection selection = viewer.getSelection();
                Object obj = ((IStructuredSelection) selection).getFirstElement();
                if (obj instanceof Accident) {
                    Accident accident = (Accident) obj;
                    InfoInput infoInput = new InfoInput(accident);
                    IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
                    try {
                        page.openEditor(infoInput, InfoEditor.ID);
                    } catch (PartInitException e) {
                        System.err.println(e.getMessage());
                    }
                }
            }

        };

        editAccidentAction.setText(Messages.AccidentEditor_0);
        editAccidentAction.setDescription(Messages.AccidentEditor_1);
        editAccidentAction.setImageDescriptor(Activator.getImageDescriptor("/icons/accident.gif")); //$NON-NLS-1$

        refreshAction = new Action() {

            /*
             * (non-Javadoc)
             * 
             * @see org.eclipse.jface.action.Action#run()
             */
            @Override
            public void run() {
                viewer.refresh();
            }
        };

        refreshAction.setText(Messages.AccidentEditor_5);
        refreshAction.setDescription(Messages.AccidentEditor_5);
        refreshAction.setImageDescriptor(Activator.getImageDescriptor("/icons/refresh_blue.gif")); //$NON-NLS-1$

        deleteActoin = new Action() {

            /*
             * (non-Javadoc)
             * 
             * @see org.eclipse.jface.action.Action#run()
             */
            @Override
            public void run() {
                ISelection selection = viewer.getSelection();
                Object obj = ((IStructuredSelection) selection).getFirstElement();
                if (obj instanceof Accident) {
                    Accident accident = (Accident) obj;
                    try {
                        CDOHibernateUtil.deleteAccident(accident);
                    } catch (CommitException e) {
                        // add failed log
                        e.printStackTrace();
                    }
                    refreshAction.run();
                }
            }

        };
        deleteActoin.setText(Messages.AccidentEditor_6);
        deleteActoin.setDescription(Messages.AccidentEditor_7);
        deleteActoin.setImageDescriptor(Activator.getImageDescriptor("/icons/delete.gif")); //$NON-NLS-1$
    }

    /**
     * DOC liaoqc Comment method "addColumns".
     * 
     * @param table
     */
    private void addColumns(Table table) {
        TableColumn phenomenonColumn = new TableColumn(table, SWT.LEFT, 0);
        phenomenonColumn.setResizable(true);
        phenomenonColumn.setText(Messages.AccidentEditor_3);
        phenomenonColumn.setWidth(300);

        TableColumn componentColumn = new TableColumn(table, SWT.LEFT, 1);
        componentColumn.setResizable(true);
        componentColumn.setText(Messages.AccidentEditor_4);
        componentColumn.setWidth(80);

        int i = 2;
        Configuration configuration = CDOHibernateUtil.getConfiguration();
        EList<ConfigElement> configElements = configuration.getElements();
        for (Iterator<ConfigElement> iterator = configElements.iterator(); iterator.hasNext();) {
            ConfigElement configElement = (ConfigElement) iterator.next();
            TableColumn configElementColumn = new TableColumn(table, SWT.LEFT, i++);
            configElementColumn.setResizable(true);
            configElementColumn.setText(configElement.getName());
            configElementColumn.setWidth(100);
        }

    }

    @Override
    public void setFocus() {
        viewer.getControl().setFocus();
    }

}
